package com.rc.web.service.impl;

import com.google.common.collect.ImmutableMap;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rc.common.constant.Code;
import com.rc.common.constant.CollectType;
import com.rc.common.constant.PlantType;
import com.rc.common.exception.BusinessException;
import com.rc.common.model.ImageModel;
import com.rc.common.util.JsonUtil;
import com.rc.common.util.PositionUtil;
import com.rc.common.util.RabbitMqHelper;
import com.rc.pojo.dto.adoption.AdoptionAddDTO;
import com.rc.pojo.dto.adoption.AdoptionListDTO;
import com.rc.pojo.dto.adoption.AdoptionPageQuery;
import com.rc.pojo.dto.adoption.AdoptionUpdateDTO;
import com.rc.pojo.po.Adoption;
import com.rc.pojo.po.Plant;
import com.rc.pojo.vo.adoption.AdoptionDetailVO;
import com.rc.pojo.vo.adoption.AdoptionListVO;
import com.rc.pojo.vo.adoption.AdoptionPageVO;
import com.rc.pojo.vo.adoption.AdoptionVO;
import com.rc.web.converter.AdoptionConverter;
import com.rc.web.mapper.AdoptionMapper;
import com.rc.web.service.AdoptionService;
import com.rc.web.service.CollectService;
import com.rc.web.service.PlantService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 领养服务实现类
 * 提供领养相关的业务逻辑实现
 */
@Service
@RequiredArgsConstructor(onConstructor_= {@Lazy})
public class AdoptionServiceImpl extends ServiceImpl<AdoptionMapper, Adoption> implements AdoptionService {
    // 领养转换器
    private final AdoptionConverter adoptionConverter;
    // 收藏服务
    private final CollectService collectService;
    // 植物服务
    private final PlantService plantService;
    // RabbitMQ工具类
    private final RabbitMqHelper rabbitMqHelper;

    /**
     * 添加领养信息
     * @param dto 领养添加DTO
     */
    @Override
    public void add(AdoptionAddDTO dto) {
        var adoption = adoptionConverter.addDTO2PO(dto);

        var plant = plantService.getById(dto.getPlantId());

        //如果植物不存在 或者植物是其他农庄 或者植物类型不是水果则报错
        if (plant == null ||!Objects.equals(plant.getType(),PlantType.FRUIT)){
            throw new BusinessException(Code.NO_SUCH_PLANT);
        }

        this.save(adoption);
    }

    /**
     * 根据ID删除领养信息
     * @param id 领养ID
     */
    @Override
    public void deleteOneById(Long id) {
        var adoption = this.getById(id);

        if (adoption == null){
            throw new BusinessException(Code.NO_SUCH_ADOPTION);
        }

        var success = this.removeById(id);

//        //2、将可领养的果书设置为不可领养状态
//        fruitTreeService.setUnAdoption(adoption.getTreeType());
    }

    /**
     * 更新领养信息
     * @param dto 领养更新DTO
     */
    @Override
    public void updateById(AdoptionUpdateDTO dto) {
        var adoption = adoptionConverter.updateDTO2PO(dto);
        this.updateById(adoption);

        var msg = ImmutableMap.<String,Object>builder()
                .put("itemId", adoption.getId())
                .put("type", CollectType.ADOPTION)
                .build();
        rabbitMqHelper.sendMessage("item.direct","update", msg);
    }

    /**
     * 获取领养列表
     * @param dto 领养列表查询条件
     * @return 领养列表VO
     */
    @Override
    public List<AdoptionListVO> getList(AdoptionListDTO dto) {
        var rowList = mapper.selectListByTreeNameAndTreeType(dto.getTreeName(), dto.getTreeType());

        var currentLng = dto.getLng();
        var currentLat = dto.getLat();

        return rowList.stream()
                .map(row ->{
                    var vo = row.toEntity(AdoptionListVO.class);
                    var rowString = row.getString("imgs");
                    var imgs = JsonUtil.toObjList(rowString,ImageModel.class);
                    var cover = imgs.stream().findFirst().orElse(new ImageModel()).getUrl();
                    vo.setCover(cover);

                    //设置距离
                    var distance = PositionUtil.distance(currentLng, currentLat,row.getDouble("lng"), row.getDouble("lat"));
                    vo.setDistance(distance);
                    return vo;
                }).toList();
    }

    /**
     * 分页查询领养信息
     * @param query 分页查询条件
     * @return 分页结果
     */
    @Override
    public Page<AdoptionPageVO> getPage(AdoptionPageQuery query) {
        return mapper.selectPage(query);
    }

    /**
     * 根据ID获取领养信息
     * @param id 领养ID
     * @return 领养VO
     */
    @Override
    public AdoptionVO getOneById(Long id) {
        var byId = this.getById(id);
        return adoptionConverter.toVO(byId);
    }

    /**
     * 获取领养详情
     * @param id 领养ID
     * @return 领养详情VO
     */
    @Override
    public AdoptionDetailVO getDetail(Long id) {
        var row = mapper.selectDetail(id);

        if (row == null){
            throw new BusinessException(Code.NO_SUCH_ADOPTION);
        }

        var detailVO = row.toEntity(AdoptionDetailVO.class);
        var collect = collectService.isCollect(id, CollectType.ADOPTION);
        detailVO.setIsCollect(collect);
        return detailVO;
    }
}
